﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Web.Profile;
using System.Web.Security;


namespace HRMService
{
    public partial class MainService : IUser
    {
        public bool User_Delete(string UserName)
        {
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_Employee_DeleteUserName", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@Employee_UserName", UserName);
            try
            {
                dbConn.Open();
                dbCmd.ExecuteNonQuery();
            }
            finally
            {
                dbConn.Close();
            }

            return Membership.DeleteUser(UserName, true);
        }

        public DataSet User_GetList(out int ItemCount, int currentPage, int pageSize, string RegionCode, int BranchID)
        {
            DataSet retVal = null;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_User_GetList", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@CurrentPage", currentPage);
            dbCmd.Parameters.AddWithValue("@PageSize", pageSize);
            dbCmd.Parameters.AddWithValue("@BranchID", BranchID);
            dbCmd.Parameters.AddWithValue("@RegionCode", RegionCode);
            try
            {
                retVal = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(dbCmd);
                da.Fill(retVal);
                ItemCount = Convert.ToInt32(retVal.Tables[1].Rows[0][0]);
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;
        }

        public string[] User_GetAllRoles()
        {
            return Roles.GetAllRoles();
        }

        public string[] User_GetUserRoles(string UserName)
        {
            return Roles.GetRolesForUser(UserName);
        }

        public string User_CreateRole(string roleName)
        {
            string retVal = "";
            try
            {
                Roles.CreateRole(roleName);
                retVal = "true";
            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }
            return retVal;
        }

        public string User_DeleteRole(string roleName)
        {
            string retVal = "false";
            try
            {
                if (Roles.DeleteRole(roleName))
                    retVal = "true";
            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }
            return retVal;
        }

        public string User_AddUserToRole(string userName, string roleName)
        {
            string retVal = "";
            try
            {
                Roles.AddUserToRole(userName, roleName);
                retVal = "true";
            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }

            return retVal;
        }

        public string User_RemoveUserFromRole(string userName, string roleName)
        {
            string retVal = "";
            try
            {
                Roles.RemoveUserFromRole(userName, roleName);
                retVal = "true";
            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }

            return retVal;
        }

        public bool User_IsUserInRole(string userName, string roleName)
        {
            return Roles.IsUserInRole(userName, roleName);
        }
        public bool User_ChangePassword(string userName, string oldPass, string passWord)
        {
            return (Membership.GetUser(userName).ChangePassword(oldPass, passWord));
        }
        public string User_Update(string userName, string passWord, string eMail, string fullName, string Address, string Phone, string BranchID, string DepartmentID, string position, string RegionCode)
        {
            string retVal = "";
            string oldPass;
            try
            {
                MembershipUser user = Membership.GetUser(userName);

                oldPass = user.GetPassword();

                if (user.ChangePasswordQuestionAndAnswer(oldPass, fullName, userName))
                {
                    if (user.ChangePassword(oldPass, passWord))
                    {
                        user.Email = eMail;
                        Membership.UpdateUser(user);

                        ProfileBase settings = ProfileBase.Create(userName);
                        settings["FullName"] = fullName;
                        settings["Address"] = Address;
                        settings["Phone"] = Phone;
                        settings["BranchID"] = BranchID;
                        settings["PositionID"] = position;
                        settings["DepartmentID"] = DepartmentID;
                        settings["RegionCode"] = RegionCode;
                        settings.Save();
                        retVal = "";
                    }
                    else
                        retVal = "False";
                }
                else
                    retVal = "False";
            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }

            return retVal;
        }

        public string User_Create(string userName, string passWord, string eMail, string fullName, string Address, string Phone, string BranchID, string DepartmentID,string position, string RegionCode)
        {
            string retVal = "";
            try
            {
                MembershipCreateStatus status;

                Membership.CreateUser(userName, passWord, eMail, fullName, userName, true, out status);

                retVal = status.ToString();

                ProfileBase settings = ProfileBase.Create(userName);
                settings["FullName"] = fullName;
                settings["Address"] = Address;
                settings["Phone"] = Phone;
                settings["BranchID"] = BranchID;
                settings["PositionID"] = position;
                settings["DepartmentID"] = DepartmentID;
                settings["RegionCode"] = RegionCode;
                settings.Save();

            }
            catch (Exception ex)
            {
                retVal = ex.Message;
            }
            return retVal;
        }

        public DataSet User_GetInfo(string userName)
        {
            MembershipUser user = Membership.GetUser(userName);
            DataTable dataTable = new DataTable("Users");
            dataTable.Columns.Add("UserName", typeof(String));
            dataTable.Columns.Add("Password", typeof(String));
            dataTable.Columns.Add("Email", typeof(String));
            dataTable.Columns.Add("FullName", typeof(String));
            dataTable.Columns.Add("Address", typeof(String));
            dataTable.Columns.Add("Phone", typeof(String));
            dataTable.Columns.Add("BranchID", typeof(String));
            dataTable.Columns.Add("Position", typeof(String));
            dataTable.Columns.Add("DepartmentID", typeof(String));
            dataTable.Columns.Add("RegionCode", typeof(String));

            ProfileBase settings = ProfileBase.Create(userName);
            string _branchID = "0";
            string _departmentID = "0";
            string _position = "0";
            string _fullName = (string)settings["FullName"];
            string _address = (string)settings["Address"];
            string _phone = (string)settings["Phone"];
            string _RegionCode = (string)settings["RegionCode"];

            if (settings["BranchID"] != DBNull.Value)
            {
                _branchID = (string)settings["BranchID"];
                _position = (string)settings["PositionID"];
                _departmentID = (string)settings["DepartmentID"];
            }

            dataTable.Rows.Add(new String[] { user.UserName, user.GetPassword(), user.Email, _fullName, _address, _phone, _branchID, _position, _departmentID, _RegionCode });

            DataSet ds = new DataSet();
            ds.Tables.Add(dataTable);
            return ds;
        }

        public UserInfo User_GetUserInfo(string userName)
        {
            UserInfo retVal = null;
            MembershipUser user = Membership.GetUser(userName);


            if (user != null)
            {
                ProfileBase settings = ProfileBase.Create(userName);
                retVal = new UserInfo();
                retVal.FullName = (string)settings["FullName"];
                retVal.Address = (string)settings["Address"];
                retVal.Phone = (string)settings["Phone"];
                retVal.RegionCode = (string)settings["RegionCode"];
                if (settings["BranchID"] != DBNull.Value)
                {
                    retVal.BranchID = (string)settings["BranchID"];
                    retVal.Position = (string)settings["PositionID"];
                    retVal.DepartmentID = (string)settings["DepartmentID"];
                }
                else
                {
                    retVal.BranchID = "0";
                    retVal.Position = "0";
                    retVal.DepartmentID = "0";
                }
                retVal.PassWord = user.GetPassword();
                retVal.Email = user.Email;
            }
            return retVal;
        }

        public DataSet User_GetAllUsersByBranch(int _branchID, int pageIndex, int pageSize, out int totalRecord)
        {
            MembershipUserCollection userCollection = Membership.GetAllUsers(pageIndex, pageSize, out totalRecord);
            DataTable dataTable = new DataTable("Users");
            dataTable.Columns.Add("UserName", typeof(String));
            dataTable.Columns.Add("FullName", typeof(String));
            dataTable.Columns.Add("Address", typeof(String));
            dataTable.Columns.Add("Phone", typeof(String));
            dataTable.Columns.Add("Email", typeof(String));
            dataTable.Columns.Add("Branch_Name", typeof(String));
            dataTable.Columns.Add("Position", typeof(String));
            dataTable.Columns.Add("RegionCode", typeof(String));

            foreach (MembershipUser user in userCollection)
            {
                ProfileBase settings = ProfileBase.Create(user.UserName);

                string _fullName = (string)settings["FullName"];
                string _address = (string)settings["Address"];
                string _phone = (string)settings["Phone"];
                string _position = (string)settings["PositionID"];
                string _RegionCode = (string)settings["RegionCode"];
                string _BranchIDManage = (string)settings["BranchIDManage"];
                string _branchName = "";
                int _branch_ID = 0;
                if (int.TryParse(settings["BranchID"].ToString(), out _branch_ID))
                    _branch_ID = Convert.ToInt32(settings["BranchID"]);

                if (_branchID == 0)
                    dataTable.Rows.Add(new String[] { user.UserName, _fullName, _address, _phone, user.Email, _branchName, _position });
                else
                {
                    BranchInfo _BranchInfo = new BranchInfo();
                    _BranchInfo = Branch_GetInfo(_branchID);
                    _branchName = _BranchInfo.Name;
                    if (_branch_ID == _branchID)
                        dataTable.Rows.Add(new String[] { user.UserName, _fullName, _address, _phone, user.Email, _branchName, _position });
                }
            }
            DataSet ds = new DataSet();
            ds.Tables.Add(dataTable);
            return ds;
        }
        public bool User_Exist(string _username)
        {
            bool retVal = false;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_User_Exist", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@Username", _username);
            try
            {
                dbConn.Open();
                if (Convert.ToInt32(dbCmd.ExecuteScalar()) > 0)
                    retVal = true;
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;

        }


        //Service cho phần phân quyền user quản lý chi nhánh
        public int UserBranch_Create(string username, string branch_code)
        {
            int retVal = 0;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_UserBranch_Create", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@Username", username);
            dbCmd.Parameters.AddWithValue("@Branch_Code", branch_code);
            try
            {
                dbConn.Open();
                retVal = Convert.ToInt32(dbCmd.ExecuteScalar());
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;
        }

        public int UserBranch_Delete(string username, string branch_code)
        {
            int retVal = 0;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_UserBranch_Delete", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@Username", username);
            dbCmd.Parameters.AddWithValue("@Branch_Code", branch_code);
            try
            {
                dbConn.Open();
                retVal = Convert.ToInt32(dbCmd.ExecuteScalar());
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;
        }

        public DataSet UserBranch_GetListManage(string regioncode,string branchname, string username, int type)
        {
            DataSet retVal = null;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_UserBranch_GetListManage", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@RegionCode", regioncode);
            dbCmd.Parameters.AddWithValue("@BranchName", branchname);
            dbCmd.Parameters.AddWithValue("@Username", username);
            dbCmd.Parameters.AddWithValue("@Type", type);
            try
            {
                dbConn.Open();
                retVal = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(dbCmd);
                da.Fill(retVal);
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;
        }

        public DataSet UserBranch_GetListChuyenQuan(int type, string username)
        {
            DataSet retVal = null;
            SqlConnection dbConn = new SqlConnection(Properties.Settings.Default.ConnectionString);
            SqlCommand dbCmd = new SqlCommand("HRM_UserBranch_GetListChuyenQuan", dbConn);
            dbCmd.CommandType = CommandType.StoredProcedure;
            dbCmd.Parameters.AddWithValue("@Type", type);
            dbCmd.Parameters.AddWithValue("@Username", username);
            try
            {
                dbConn.Open();
                retVal = new DataSet();
                SqlDataAdapter da = new SqlDataAdapter(dbCmd);
                da.Fill(retVal);
            }
            finally
            {
                dbConn.Close();
            }
            return retVal;
        }
        
    }
}
